package com.api.controller;

import com.api.entity.PageVo;
import com.api.entity.Result;
import com.api.entity.Users;
import com.api.entity.UsersDto;
import com.api.service.RolesService;
import com.api.service.UserRolesService;
import com.api.service.UsersService;
import com.api.tool.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.SessionStatus;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api("用户的增删改查操作")
/* @RequestMapping("/users") */
public class UsersController {

    @Autowired
    private UsersService userService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private UserRolesService userRolesService;

    @ApiOperation("用户名和密码登录")
    @PostMapping("/login")
    public Object login(@ApiParam("登录用户名") @RequestParam("un") String un, @ApiParam("登录密码") @RequestParam("pwd") String pwd, @ApiParam("mac地址") @RequestParam("macAddress") String macAddress, HttpSession session) {
        if (StringUtils.isEmpty(macAddress)) {
            new Result("mac地址为空", "", false);
        }
        Users user = new Users();
        user.setLoginName(un);
        user.encryptPwd(pwd);
        Users u = userService.login(user);
        if (u != null) {
            if (StringUtils.isEmpty(u.getMacAddress())) {
                userService.updateMac(un, macAddress);
            } else if (!macAddress.equalsIgnoreCase(u.getMacAddress())) {
                return new Result("该设备未绑定", "", false);
            }
            //String tok = MD5Utils.getMD5Str(un);
            String uid = u.getId();
            String tok = getToken(un,uid);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("uid", uid);
            map.put("token", tok);
            map.put("state", u.getState());
            map.put("name", u.getLoginName());
            session.setAttribute("token", tok);
            session.setMaxInactiveInterval(5 * 60);
            userService.updateUsersTimeById(uid);
            Result result = new Result("登录成功", map, true);
            return result;
        } else {
            Result result = new Result("用户名或密码错误", "", false);
            return result;
        }
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public Object updatePassword(@ApiParam("用户名") @RequestParam("un") String un, @ApiParam("原密码") @RequestParam("oriPwd") String oriPwd, @ApiParam("新️密码") @RequestParam("pwd") String pwd, HttpServletRequest request) {
        Users user = new Users();
        user.setLoginName(un);
        user.encryptPwd(oriPwd);
        Users u = userService.login(user);
        if (u == null) {
            return new Result("原密码错误", 3, false);
        }
        String newPwd = MD5Utils.getMD5Str(pwd);
        int i = userService.resetPwd(un, newPwd);
        if (i > 0) {
            Result result = new Result("重置成功", 3, true);
            return result;
        } else {
            Result result = new Result("重置失败", 3, false);
            return result;
        }
    }

    @ApiOperation("重置密码")
    @PostMapping("/ResetPassword")
    public Object againpwd(@ApiParam("用户名") @RequestParam("un") String un, @ApiParam("新️密码") @RequestParam("pwd") String pwd, HttpServletRequest request) {
        String newPwd = MD5Utils.getMD5Str(pwd);
        int i = userService.resetPwd(un, newPwd);
        if (i > 0) {
            Result result = new Result("重置成功", 3, true);
            return result;
        } else {
            Result result = new Result("重置失败", 3, false);
            return result;
        }
    }

    @ApiOperation("解绑mac地址")
    @PostMapping("/resetMacAddress")
    public Object resetMacAddress(@ApiParam("用户名") @RequestParam("un") String un, HttpServletRequest request) {
        int i = userService.resetMac(un);
        if (i > 0) {
            Result result = new Result("重置成功", 3, true);
            return result;
        } else {
            Result result = new Result("重置失败", 3, false);
            return result;
        }
    }

    @ApiOperation("锁定用户")
    @PostMapping("/LockUser")
    @ApiIgnore
    public Object updateLockUsertrue(@ApiParam("用户名") @RequestParam("un") String un, HttpServletRequest request, @ApiParam("Token 密钥") @RequestParam("token") String token) {

        String sessionToken = (String) request.getSession().getAttribute("token");
        if (sessionToken == "" || sessionToken == null) {
            Result result = new Result("您的Token已过期，请重新获取并登录", 0, false);
            return result;
        } else if (sessionToken.equals(token)) {
            int i = userService.updateLockUsertrue(un);
            if (i > 0) {
                Result result = new Result("锁定成功", "", true);
                return result;
            } else {
                Result result = new Result("锁定失败", "", false);
                return result;
            }
        } else {
            Result result = new Result("请核实 Token 是否正确", "", false);
            return result;
        }
    }

    @ApiOperation("解锁用户")
    @PostMapping("/UnLockUser")
    @ApiIgnore
    public Object updateLockUserfalse(@ApiParam("用户名") @RequestParam("un") String un, HttpServletRequest request, @ApiParam("Token 密钥") @RequestParam("token") String token) {

        String sessionToken = (String) request.getSession().getAttribute("token");
        if (sessionToken == "" || sessionToken == null) {
            Result result = new Result("您的Token已过期，请重新获取并登录", 0, false);
            return result;
        } else if (sessionToken.equals(token)) {
            int i = userService.updateLockUserfalse(un);
            if (i > 0) {
                Result result = new Result("解锁成功", "", true);
                return result;
            } else {
                Result result = new Result("解锁失败", "", false);
                return result;
            }
        } else {
            Result result = new Result("请核实 Token 是否正确", "", false);
            return result;
        }
    }

    @ApiOperation("删除用户(逻辑删除)")
    @PostMapping("/DeleteUser")
    public Object updateState(@ApiParam("用户id") @RequestParam("uid") String uid, HttpServletRequest request) {

        int i = userService.updateState(uid);
        if (i > 0) {
//                userRolesService.deleteAllUsersRolesByid(uid);
            Result result = new Result("删除成功", "", true);
            return result;
        } else {
            Result result = new Result("删除失败", "", false);
            return result;
        }

    }

    @ApiOperation("多条件动态分页查询所有信息")
    @PostMapping("/GetUsersLayUI")
    @ApiIgnore
    public Object findAllBySomeOrder(@ApiParam("排序参数") @RequestParam(value = "orderBy", required = false) String orderBy, @ApiParam("用户名") @RequestParam(value = "userName", required = false) String userName, @ApiParam("起始时间") @RequestParam(value = "beginDate", required = false) String beginDate, @ApiParam("结束时间") @RequestParam(value = "endDate", required = false) String endDate, @ApiParam("是/否 锁定") @RequestParam(value = "isLock", required = false) String isLock, @ApiParam("分页Page") @RequestParam("page") int page, @ApiParam("分页 limit") @RequestParam("limit") int limit, HttpServletRequest request, @ApiParam("Token 密钥") @RequestParam("token") String token) {

        String sessionToken = (String) request.getSession().getAttribute("token");
        if (sessionToken == "" || sessionToken == null) {
            Result result = new Result("您的Token已过期，请重新获取并登录", 0, false);
            return result;
        } else if (sessionToken.equals(token)) {
            UsersDto user = new UsersDto();
            user.setOrderBy(orderBy);
            user.setUserName(userName);
            user.setBeginDate(beginDate);
            user.setEndDate(endDate);
            user.setIsLock(isLock);
            PageVo pageVo = new PageVo();
            pageVo.setPage(page);
            pageVo.setPageSize(limit);
            user.setPageVo(pageVo);
            List<Users> list = userService.findAllBySomeOrder(user);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", 0);
            map.put("count", list.size());
            map.put("data", list);
            map.put("message", 1);
            return map;
        } else {
            Result result = new Result("请核实 Token 是否正确", "", false);
            return result;
        }
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/UpdateUser")
    public Object updateUsersSomeOrderByid(@ApiParam("邮箱") @RequestParam("email") String email, @ApiParam("用户名") @RequestParam("loginName") String loginName, @ApiParam("手机号") @RequestParam("mtel") String mtel, HttpServletRequest request) {
        Users user = new Users();
        user.setProtectEMail(email);
        user.setProtectMTel(mtel);
        user.setLoginName(loginName);
        int i = userService.updateUsersSomeOrderByid(user);
        if (i > 0) {
            Result result = new Result("修改成功", "", true);
            return result;
        } else {
            Result result = new Result("修改失败", "", false);
            return result;
        }

    }

    @ApiOperation("创建用户信息")
    @PostMapping("/CreateUser")
    public Object addUsers(@ApiParam("用户名") @RequestParam(value = "loginName") String loginName, @ApiParam("密码") @RequestParam(value = "pwd") String pwd, @ApiParam("邮箱") @RequestParam(value = "email") String email, @ApiParam("手机号") @RequestParam(value = "mtel") String mtel, HttpServletRequest request) {
        Users u = userService.findAllByUname(loginName);
        if (u != null) {
            return new Result("添加失败，用户已存在", "", false);
        }
        String id16 = id16();
        Users user = new Users();
        user.setId(id16);
        user.setLoginName(loginName);
        user.encryptPwd(pwd);
        user.setProtectMTel(mtel);
        user.setProtectEMail(email);
        int i = userService.addUsers(user);
        if (i > 0) {
            Result result = new Result("添加成功", "", true);
            return result;
        } else {
            Result result = new Result("添加失败", "", false);
            return result;
        }
    }

    @ApiOperation("获取数据 库秘钥")
    @PostMapping("/getToken")
    @ApiIgnore
    public Object getSercret(@ApiParam("登录用户名") @RequestParam("un") String un, @ApiParam("密码") @RequestParam("pwd") String pwd) {
        Users user = new Users();
        user.setLoginName(un);
        user.encryptPwd(pwd);
        Users u = userService.login(user);
        if (u != null) {
            String str = MD5Utils.getMD5Str(un);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("title", "您的密钥为：");
            map.put("token", str);
            map.put("over", "请妥善保存！");
            return map;
        } else {
            return "用户名或密码错误";
        }
    }

    /**
     * 退出登录清空session	/	Token
     */
    @ApiOperation("退出登录清空session")
    @PostMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus) {
        session.invalidate();
        sessionStatus.setComplete();
        return "1";
    }

    public String id16() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
        String fd = sdf.format(date);
        fd += String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        return fd;
    }

    @ApiOperation("注册用户名不能重复")
    @PostMapping("/findAllByUname")
    public Object findAllByUname(@ApiParam("登录用户名") @RequestParam("name") String name) {
        Users u = userService.findAllByUname(name);
        if (u == null) {
            Result result = new Result("", "", true);
            return result;
        } else {
            Result result = new Result("", "", false);
            return result;
        }
    }

    @ApiOperation("注册邮箱不能重复")
    @PostMapping("/findAllByUemal")
    public Object findAllByUemal(@ApiParam("登录用户名") @RequestParam("emal") String emal) {
        Users u = userService.findAllByUemal(emal);
        if (u == null) {
            Result result = new Result("", "", true);
            return result;
        } else {
            Result result = new Result("", "", false);
            return result;
        }
    }

    @ApiOperation("注册手机号不能重复")
    @PostMapping("/findAllByUnumber")
    public Object findAllByUnumber(@ApiParam("登录用户名") @RequestParam("tel") String tel) {
        Users u = userService.findAllByUnumber(tel);
        if (u == null) {
            Result result = new Result("", u, true);
            return result;
        } else {
            Result result = new Result("", "", false);
            return result;
        }
    }

    /**
     * 根据userId和userName创建token
     * @param userName
     * @param userId
     * @return
     */
    public static String getToken(String userName,String userId){
        String token  = userName+"&"+userId;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateTime = sdf.format(new Date());
        token = token +"&"+dateTime;
        return Base64Utils.encodeToString(token.getBytes());
    }


    @ApiOperation("通过Token获取用户信息")
    @PostMapping("/getUserByToken")
    public Object getUserByToken(@ApiParam("用户Token") @RequestParam("token") String token, HttpServletRequest request) {
        String sessionToken = (String) request.getSession().getAttribute("token");
        System.out.println("request.getSession():"+sessionToken);
        Map map = new HashMap();
        if (sessionToken == "" || sessionToken == null) {
            Result result = new Result("您的Token已过期，请重新获取并登录", 0, false);
            return result;
        } else if (sessionToken.equals(token)) {
            byte[] bytes = Base64Utils.decodeFromString(token);
            String str = new String(bytes);
            String[] split = str.split("&");
            if(split.length>1){
                Users users = userService.findUserByIdAndName(split[1], split[0]);
                if(users !=null){
                    map.put("userName",users.getLoginName());
                    map.put("userId",users.getId());
                    map.put("flag",0);
                    map.put("msg","成功");
                }else {
                    map.put("flag",1);
                    map.put("msg","无法根据Token解析出用户信息");
                }
                return map;
            }
        }else{
            map.put("flag",1);
            map.put("msg","您的Token已过期");
            return map;
        }
        return null;
    }

    public static void main(String[] args) {
        String token = getToken("zhenchl", "0310093425706141");
        System.out.println(token);
        byte[] bytes = Base64Utils.decodeFromString(token);
        String str = new String(bytes);
        System.out.println(str);
        String[] split = str.split("&");
        Map map = new HashMap();
        if(split.length>1){
            map.put("userName",split[0]);
            map.put("userId",split[1]);
        }
        System.out.println(map.get("userName") + ":::" + map.get("userId"));
        System.out.println(bytes.toString());
    }



}
